% This file loads in the actuarial table probabilities over time
%
%

clear gam_mat

gam_probs_all = csvread('../data/demographic/actuarial_table_over_time.csv',1,1) ;

age = (0:119)' ;
idxa = 1:length(age) ;

timevec = 1900:10:2070 ;
idxt = 1:length(timevec) ;

timevec_new = 1860:2070 ;
idxt_new = 1:length(timevec_new) ;

timevec_dat = 1940:2070;

for jj=1:length(age)
gam_mat(jj,:) = interp1(timevec', gam_probs_all(jj,:)', timevec_new','linear','extrap') ;
end

gam_mat(gam_mat>1) = 1 ;

gam_sh_mat = gam_mat(idxa(age==16):idxa(age==95),find(timevec_new==1940):find(timevec_new==2070)) - ...
    repmat(gam_mat(idxa(age==16):idxa(age==95),find(timevec_new==2070)),[1 (2070-1940+1)]) ;

gam_mat_ = zeros(size(gam_mat));
for i=1:length(gam_mat(:,1))
    gam_mat_(i,:) = prod(1-gam_mat(1:i,:));
end
life_exp = sum(gam_mat_);

gam_mat_b = zeros(size(gam_mat));
for i=65:length(gam_mat(:,1))
    gam_mat_b(i,:) = prod(1-gam_mat(65:i,:));%./gam_mat_(65,:);
end

life_exp_at_65 = sum(gam_mat_b);

gam_mat_orig = gam_mat ;

gam_mat = gam_mat(idxa(age==16):idxa(age==95),find(timevec_new==1940):find(timevec_new==2070)) ;

clear gam_mat_new

for ii=1:length(gam_mat(:,1))
	gam_mat_new(ii,:) = gam_mat_orig(idxa(age==(16+ii-1)),(find(timevec_new==1940)-ii+1):(find(timevec_new==1940)-ii+length(gam_mat(1,:)))) ;
end

gam_mat = gam_mat_new ;

life_exp_at_65 = life_exp_at_65(:,find(timevec_new==1940):find(timevec_new==2070)) ;
